package com.atguigu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVO;
import com.atguigu.common.to.SkuReductionTO;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.product.dao.SpuInfoDao;
import com.atguigu.product.entity.*;
import com.atguigu.product.feign.CouponFeignService;
import com.atguigu.product.feign.SearchFeignService;
import com.atguigu.product.feign.WareFeignService;
import com.atguigu.product.service.*;
import com.atguigu.product.vo.spvsavevo.Bounds;
import com.atguigu.product.vo.spvsavevo.Images;
import com.atguigu.product.vo.spvsavevo.Skus;
import com.atguigu.product.vo.spvsavevo.SpuSaveVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    SpuInfoDescService spuInfoDescService;

    @Resource
    SpuImagesService spuImagesService;

    @Resource
    AttrService attrService;

    @Resource
    ProductAttrValueService attrValueService;

    @Resource
    SkuInfoService skuInfoService;

    @Resource
    SkuImagesService skuImagesService;

    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    CouponFeignService couponFeignService;

    @Resource
    BrandService brandService;

    @Resource
    CategoryService categoryService;

    @Resource
    WareFeignService wareFeignService;

    @Resource
    SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息
        SpuInfoEntity spuInfoEntity = BeanUtil.copyProperties(vo, SpuInfoEntity.class);
        saveBaseSpuInfo(spuInfoEntity);
        //2、spu的描述图片、
        SpuInfoDescEntity spuInfoDescEntity = SpuInfoDescEntity.builder().spuId(spuInfoEntity.getId()).decript(String.join(",", vo.getSpuDescription())).build();
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        //3、保存spu的图片集
        spuImagesService.saveImages(spuInfoEntity.getId(), vo.getImages());
        //4、保存spu的规格参数
        List<ProductAttrValueEntity> productAttrValueEntities = vo.getBaseAttrs().stream().map(attr -> ProductAttrValueEntity.builder().attrId(attr.getAttrId())
                .attrName(attrService.getById(attr.getAttrId()).getAttrName()).attrValue(attr.getAttrValues()).quickShow(attr.getShowDesc()).spuId(spuInfoEntity.getId())
                .build()).collect(Collectors.toList());
        attrValueService.saveBatch(productAttrValueEntities);
        //5、保存spu的积分信息
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = BeanUtil.copyProperties(bounds, SpuBoundTo.class);
        R r = couponFeignService.saveSpuBound(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //5、保存当前spu对应的sku消息
        List<Skus> skus = vo.getSkus();
        if (CollUtil.isNotEmpty(skus)) {
            for (Skus sku : skus) {
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = BeanUtil.copyProperties(sku, SkuInfoEntity.class);
                skuInfoEntity.setSkuId(spuInfoEntity.getBrandId())
                        .setCatalogId(spuInfoEntity.getCatalogId()).setSaleCount(0L).setSpuId(spuInfoEntity.getId()).setSkuDefaultImg(defaultImg);
                //5.1 sku的基本信息
                skuInfoService.save(skuInfoEntity);
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(img -> SkuImagesEntity.builder()
                                .skuId(skuInfoEntity.getSkuId()).imgUrl(img.getImgUrl()).defaultImg(img.getDefaultImg()).build())
                        .filter(skuImagesEntity -> StrUtil.isNotEmpty(skuImagesEntity.getImgUrl())).collect(Collectors.toList());
                //5.2 sku的图片信息
                skuImagesService.saveBatch(skuImagesEntities);
                //5.3 sku的销售属性信息
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = sku.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = BeanUtil.copyProperties(attr, SkuSaleAttrValueEntity.class);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5.4 sku的优惠、满减等信息
                SkuReductionTO skuReductionTO = BeanUtil.copyProperties(sku, SkuReductionTO.class);
                if (skuReductionTO.getFullCount() >= 0 || skuReductionTO.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTO);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            }
        }
    }


    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        save(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        wrapper.and(StrUtil.isNotEmpty(key), w -> w.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key));
        String status = (String) params.get("status");
        wrapper.eq(StrUtil.isNotEmpty(status), SpuInfoEntity::getPublishStatus, status);
        String brandId = (String) params.get("brandId");
        wrapper.eq(StrUtil.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId), SpuInfoEntity::getBrandId, brandId);
        String catelogId = (String) params.get("catelogId");
        wrapper.eq(StrUtil.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId), SpuInfoEntity::getCatalogId, catelogId);
        String min = (String) params.get("min");
        wrapper.le(StrUtil.isNotEmpty(min) && BigDecimal.ZERO.compareTo(new BigDecimal(min)) < 0, SpuInfoEntity::getPrice, min);
        String max = (String) params.get("max");
        wrapper.ge(StrUtil.isNotEmpty(max) && BigDecimal.ZERO.compareTo(new BigDecimal(max)) > 0, SpuInfoEntity::getPrice, max);
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //1.查出当前spuId对应的所有sku信息,品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.list(new LambdaQueryWrapper<SkuInfoEntity>().eq(SkuInfoEntity::getSpuId, spuId));
        //2.封装每个sku的信息

        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //查询当前sku所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> attrValues = attrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = attrValues.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        Set<Long> searchAttrIds = attrService.list(new LambdaQueryWrapper<AttrEntity>().select(AttrEntity::getAttrId).in(AttrEntity::getAttrId, attrIds)
                .and(w -> w.eq(AttrEntity::getSearchType, "1"))).stream().map(AttrEntity::getAttrId).collect(Collectors.toSet());

        List<SkuEsModel.Attrs> attrs = attrValues.stream().filter(item -> searchAttrIds.contains(item.getAttrId())).map(item -> BeanUtil.copyProperties(item, SkuEsModel.Attrs.class)).collect(Collectors.toList());

        R r = wareFeignService.getSkuHasStock(skuIds);
        Map<Long, Boolean> hasStockMap = null;
        try {
            TypeReference<List<SkuHasStockVO>> typeReference = new TypeReference<List<SkuHasStockVO>>() {
            };
            hasStockMap = r.getData(typeReference).stream().collect(Collectors.toMap(
                    SkuHasStockVO::getSkuId, SkuHasStockVO::getHasStock
            ));
        } catch (Exception e) {
            log.error("库存服务查询异常：case");
        }


        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuEsModel> upproducts = skus.stream().map(sku -> {
            BrandEntity brand = brandService.getById(sku.getBrandId());
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            //发起远程调用，查询是否有库存
            SkuEsModel skuEsModel = SkuEsModel.builder().skuPrice(sku.getPrice()).skuImg(sku.getSkuDefaultImg())
                    .brandName(brand.getName()).brandImg(brand.getLogo())/*设置热度评分*/.hotScore(0L)
                    .hasStock(MapUtil.isNotEmpty(finalHasStockMap) ? finalHasStockMap.get(sku.getSkuId()) : true).catalogName(category.getName()).build();
            BeanUtil.copyProperties(sku, skuEsModel);
            //设置检索属性
            skuEsModel.setAttrs(attrs);
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5、讲数据发送给es进行保存 -> feign 调用search进行保存
        R esSaveResult = searchFeignService.productStatusUp(upproducts);
        if (esSaveResult.getCode() == 0) {
            //调用成功 修改当前sku上架状态 SpuCommentEntity::getShowStatus
            update(new LambdaUpdateWrapper<SpuInfoEntity>()
                    .setSql(StrUtil.format("set show_status = {}", ProductConstant.StatusEnum.SPU_NEW.getCode()))
                    .eq(SpuInfoEntity::getId, spuId));

        } else {
            //调用失败
            //TODO 7、重复调用 ？ 接口幂等性：重试机制？
            /*
              feign 调用流程
              1、构造请求数据，讲对象转为json；
              2、发送请求进行执行（执行成功会解码响应数据）
              3、执行请求会有重试机制

             */


        }


    }


}